﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Intelligent.OTC.Common.UnitOfWork;
using Intelligent.OTC.Domain;
using Intelligent.OTC.Business;
using Intelligent.OTC.Domain.Repositories;
using Intelligent.OTC.Domain.DataModel;
using Intelligent.OTC.WebApi.Core;
using Intelligent.OTC.Common;
using Intelligent.OTC.Common.Utils;
using System.Web;
using System.Configuration;
using System.IO;
using Intelligent.OTC.Common.Exceptions;
using System.Web.OData;
using System.Web.OData.Extensions;
using System.Linq;
using System.Web.OData.Routing;
using Intelligent.OTC.Common.Attr;

namespace Intelligent.OTC.WebApi.Controllers
{
    [UserAuthorizeFilter(actionSet: "master")]
    public class CustomerController : ApiController
    {
        public const string strArchiveOneYearSalesKey = "ArchiveOneYearSalesPath";//OneYearSales路径的config保存名

        [HttpGet]
        [PagingQueryable]
        public IEnumerable<CustomerMasterData> Get()
        {
            ICustomerService service = SpringFactory.GetObjectImpl<ICustomerService>("CustomerService");
            //  List<Customer> cust = service.GetCustomer();
            var res = service.GetCustMasterData();

            return res.AsQueryable();
        }

        [HttpGet]
        public Customer Get(string num) { 
            ICustomerService service = SpringFactory.GetObjectImpl<ICustomerService>("CustomerService");
            Customer cust = service.GetOneCustomer(num);
            return cust;
        }

        [HttpGet]
        public List<Customer> GetCustomerByCustomerNum(string cusNum)
        {
            ICustomerService service = SpringFactory.GetObjectImpl<ICustomerService>("CustomerService");
            return service.GetCustomerByCustomerNum(cusNum);
        }

        [HttpPut]
        public string Put([FromBody]Customer cust)
        {
            //try
            //{
            //    cust.Deal = AppContext.Current.User.Deal.ToString();
            //    cust.UpdateTime = AppContext.Current.User.Now;
            //    CustomerService service = SpringFactory.GetObjectImpl<CustomerService>("CustomerService");
            //    if (cust.RemoveFlg.Equals("0"))
            //    {
            //        if (service.checkDelCustomer(cust))
            //        {
            //            Helper.Log.Info(cust);
            //            Customer old = service.CommonRep.FindBy<Customer>(cust.Id);
            //            ObjectHelper.CopyObjectWithUnNeed(cust, old, new string[] { "Id", "Contacter", "CustomerGroupCfg" });
            //            service.CommonRep.Commit();
            //            return "Delete Success!";
            //        }
            //        return "Current Customer Exsit Some Information";
            //    }
            //    else {
            //        Helper.Log.Info(cust);
            //        if(cust.BillGroupCode==""){
            //            cust.BillGroupCode = null;
            //        }
            //        Customer old = service.CommonRep.FindBy<Customer>(cust.Id);
            //        ObjectHelper.CopyObjectWithUnNeed(cust, old, new string[] { "Id", "Contacter", "CustomerGroupCfg" });
            //        service.CommonRep.Commit();
            //        return "Update Success!";
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Helper.Log.Info(ex);
            //    throw new Exception(ex.Message);
            //}
            CustomerService service = SpringFactory.GetObjectImpl<CustomerService>("CustomerService");
            string message = service.UpdateCustMasterData(cust);
            return message;

        }

        [HttpPost]
        public string ExpoertCust(string custnum, string custname, string status, string group, string collector,
                                   string isic, string begintime, string endtime, string miscollector, string misgroup, 
                                     string billcode,string country)
        {
            CustomerService service = SpringFactory.GetObjectImpl<CustomerService>("CustomerService");
            return service.ExportCustomer(custnum, custname, status, group, collector, isic, begintime, endtime,
                                miscollector, misgroup, billcode,country);
        }
        [HttpPost]
        public string ImportCust(string type) 
        {
            CustomerService service = SpringFactory.GetObjectImpl<CustomerService>("CustomerService");
            return service.ImportCustHistory();
        }

        [HttpPost]
        public string Post([FromBody] Customer cust)
        {
            //try
            //{
            //    if(string.IsNullOrEmpty(cust.CustomerName)){
            //        return "Please Add Customer Name!";
            //    }
            //    cust.Deal = AppContext.Current.User.Deal.ToString();
            //    cust.CreateTime = AppContext.Current.User.Now;
            //    cust.RemoveFlg = "1";
            //    cust.IsHoldFlg = "0";
            //    CustomerService service = SpringFactory.GetObjectImpl<CustomerService>("CustomerService");
            //    Customer custflg = service.GetOneCustomer(cust.CustomerNum);
            //    if (custflg == null)
            //    {
            //        if (cust.Id == 0)
            //        {
            //            service.CommonRep.Add(cust);
            //            service.CommonRep.Commit();
            //            return "Add Success!"; 
            //        }
            //        else
            //        {
            //            Customer old = service.CommonRep.FindBy<Customer>(cust.Id);
            //            ObjectHelper.CopyObjectWithUnNeed(cust, old, new string[] { "Id" });
            //            service.CommonRep.Commit();
            //            return "Update Success！"; 
            //        }
            //        //service.CommonRep.Commit();
            //    }
            //    else{
            //        return "This customer already exsit!"; 
            //        }
                
            //}catch(Exception ex){
            //    Helper.Log.Info(ex);
            //    throw new Exception(ex.Message); 
            //}
            CustomerService service = SpringFactory.GetObjectImpl<CustomerService>("CustomerService");
            string message = service.AddCustMasterData(cust);
            return message;
        }

        [HttpGet]
        public Customer GetCustModel(string type)
        {
            if (type == "new")
            {
                Customer cust = new Customer();
                cust.Id = 0;
                return cust;
            }
            else {
                return null;
            }
        }

        //[HttpPut]
        //public void delete(int id)
        //{
        //    try
        //    {
        //        CustomerService service = SpringFactory.GetObjectImpl<CustomerService>("CustomerService");
        //        Customer old = service.CommonRep.FindBy<Customer>(id);               
        //        if (service.checkDelCustomer(old))
        //        {
        //            Customer old = service.CommonRep.FindBy<Customer>(cust.Id);
        //            ObjectHelper.CopyObjectWithUnNeed(cust, old, new string[] { "Id", "Contacter", "CustomerGroupCfg" });
        //            service.CommonRep.Commit();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Helper.Log.Info(ex);
        //        throw new Exception(ex.Message);
        //    }
        //}

        //[HttpPost]
        //public string UploadFile(string flg)
        //{
            
        //    FileType fileT = FileType.OneYearSales;
        //    string archivePath = string.Empty;
        //    string archiveFileName = string.Empty;
        //    try 
        //    {
        //        //upload file to server
        //        HttpFileCollection files = HttpContext.Current.Request.Files;
        //        archivePath = ConfigurationManager.AppSettings[strArchiveOneYearSalesKey].ToString();
        //        archivePath = archivePath + DateTime.Now.Year.ToString() + "\\" + DateTime.Now.Month.ToString();

        //        if (Directory.Exists(archivePath) == false)
        //        {
        //            Directory.CreateDirectory(archivePath);
        //        }
        //        archiveFileName = archivePath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "-" + fileT.ToString() +
        //                    "-" + AppContext.Current.User.EID + "-" + DateTime.Now.ToString("HHmmssf") + ".csv";

        //        FileService service = SpringFactory.GetObjectImpl<FileService>("FileService");
        //        service.UploadFile(files[0], archiveFileName, fileT, true);

        //        //read file content to db
        //        CustomerService cService = SpringFactory.GetObjectImpl<CustomerService>("CustomerService");
        //        cService.uploadOneYearSales();

        //        return "Uploaded file Successful!";
        //    }
        //    catch (Exception ex)
        //    {
        //        Helper.Log.Error(ex);
        //        throw new OTCServiceException("Uploaded file failed!");
        //    }
        //}

        [HttpPost]
        public void FinishSoa(string num, string site) 
        { 
        
        }

        [HttpGet]
        [PagingQueryable]
        public IEnumerable<CustomerMasterDto> GetAssign(string customers)
        {
            ICustomerService service = SpringFactory.GetObjectImpl<ICustomerService>("CustomerService");
            var res = service.GetCustMasterDataForAssign(customers);

            return res.AsQueryable();
        }
    }
}